﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System.Xml.Linq;
using Microsoft.Crm.Sdk.Messages;

namespace CRM2011.FetchXMLExecuteTool
{
    public partial class FetchXMLForm : Form
    {
        private IOrganizationService service;
        public FetchXMLForm()
        {
            InitializeComponent();
        }

        public FetchXMLForm(IOrganizationService service)
        {
            InitializeComponent();
            this.service = service;
        }

        private void btnExecute_Click(object sender, EventArgs e)
        {
            ShowWaitingBox waiting = null;
            try
            {
                waiting = new ShowWaitingBox("Fetching Results", "Please Wait....");
                waiting.Start();
                string fetchXML = txtFetchXML.Text;
                EntityCollection res = service.RetrieveMultiple(new FetchExpression(fetchXML));
                DataTable dt = new DataTable();
                dt = convertEntityCollectionToDataTable(res);
                grdResults.DataSource = dt;
                waiting.Stop();
                if(res.Entities!=null)
                txtTotRecords.Text = res.Entities.Count.ToString();
            }
            catch(Exception ex)
            {
                if (waiting != null)
                    waiting.Stop();
                MessageBox.Show(ex.Message);
                
            }
        }

        public DataTable convertEntityCollectionToDataTable(EntityCollection BEC)
        {
            DataTable dt = new DataTable();
            int total = BEC.Entities.Count;
            for (int i = 0; i < total; i++)
            {
                DataRow row = dt.NewRow();
                Entity myEntity = (Entity)BEC.Entities[i];
                var keys= myEntity.Attributes.Keys;
                foreach (var item in keys)
	            {
                    string columnName = item;
                    string value = getValuefromAttribute(myEntity.Attributes[item]);
                    if (dt.Columns.IndexOf(columnName) == -1)
                    {
                        dt.Columns.Add(item, Type.GetType("System.String"));
                    }
                    row[columnName] = value;
                }
                dt.Rows.Add(row);
            }
            return dt;
        }

        private string getValuefromAttribute(object p)
        {
            if (p.ToString() == "Microsoft.Xrm.Sdk.EntityReference")
            {
                return ((EntityReference)p).Name;
            }
            if (p.ToString() == "Microsoft.Xrm.Sdk.OptionSetValue")
            {
                return ((OptionSetValue)p).Value.ToString();
            }
            if (p.ToString() == "Microsoft.Xrm.Sdk.Money")
            {
                return ((Money)p).Value.ToString();
            }
            if (p.ToString() == "Microsoft.Xrm.Sdk.AliasedValue")
            {
                return getValuefromAttribute(((Microsoft.Xrm.Sdk.AliasedValue)p).Value.ToString());
            }
            else
            {
                return p.ToString();
            }
        }

        private string getValuefromAttribute(KeyValuePair<string, object> attribute)
        {

            return "";
        }

        
    }
}
